package com.imxinxin.common.tools.http;

import com.imxinxin.common.model.KVEntry;
import lombok.SneakyThrows;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class HttpTool {


    public static HttpResult request(HttpConfig config) throws IOException {
        return HttpSend.request(config);
    }

    @SneakyThrows
    public static String httpGet(String url, Object param, List<KVEntry<String, String>> headers) {
        HttpConfig config = new HttpConfig();
        config.setHeaders(headers);
        config.setUrlPath(url + "?" + HostTool.getFormString(param));
        return HttpSend.request(config).getResponseString();
    }

    @SneakyThrows
    public static String httpPost(String url, String param, List<KVEntry<String, String>> headers) {
        HttpConfig config = new HttpConfig();
        config.setHeaders(headers);
        config.setUrlPath(url);
        config.setSendBytes(param.getBytes(config.getSendCharset()));
        return HttpSend.request(config).getResponseString();
    }


    @SneakyThrows
    public static String objForm(Object obj) {
        if (obj == null) return null;
        Field[] fields = obj.getClass().getDeclaredFields();
        StringBuilder sb = new StringBuilder();
        for (Field field : fields) {
            field.setAccessible(true);
            sb.append(field.getName());
            sb.append("=");
            Object fv = field.get(obj);
            if (fv != null) {
                sb.append(URLEncoder.encode(fv.toString(), "UTF-8"));
            }
            sb.append("&");
        }
        return sb.toString();
    }

    @SneakyThrows
    public static String mapForm(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey() == null || entry.getValue() == null) {
                continue;
            }
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            sb.append("&");
        }
        return sb.toString();
    }

}
